using System;
using System.Diagnostics;
using System.IO;
using System.Media;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Threading;

namespace GameOverlayWPF
{
    /// <summary>
    /// 音频播放服务 - 集成增强功能支持麦克风输出
    /// </summary>
    public class AudioService
    {
        private static AudioService? _instance;
        public static AudioService Instance => _instance ??= new AudioService();

        private MediaPlayer? _mediaPlayer;
        private bool _useEnhancedMode = true; // 默认启用增强模式

        private AudioService()
        {
            // 设置进程优先级为高优先级
            SetHighPriority();
            
            // 在UI线程上初始化MediaPlayer
            System.Windows.Application.Current.Dispatcher.Invoke(() =>
            {
                _mediaPlayer = new MediaPlayer();
                _mediaPlayer.Volume = 0.8; // 设置默认音量
                System.Diagnostics.Debug.WriteLine("AudioService initialized with MediaPlayer and high priority");
            });
            
            // 初始化增强音频服务
            try
            {
                _ = EnhancedAudioService.Instance;
                System.Diagnostics.Debug.WriteLine("EnhancedAudioService 已初始化");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"EnhancedAudioService 初始化失败，将使用基础模式: {ex.Message}");
                _useEnhancedMode = false;
            }
        }
        
        /// <summary>
        /// 启用或禁用麦克风输出模式
        /// </summary>
        /// <param name="enable">是否启用</param>
        public void EnableMicrophoneOutput(bool enable)
        {
            try
            {
                if (_useEnhancedMode)
                {
                    EnhancedAudioService.Instance.EnableMicrophoneOutput(enable);
                    System.Diagnostics.Debug.WriteLine($"麦克风输出模式已{(enable ? "启用" : "禁用")}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("增强模式不可用，无法启用麦克风输出");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"设置麦克风输出失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 列出可用的音频设备
        /// </summary>
        public void ListAudioDevices()
        {
            try
            {
                if (_useEnhancedMode)
                {
                    EnhancedAudioService.Instance.ListAudioDevices();
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("增强模式不可用");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"列出音频设备失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置进程和线程为高优先级以确保音频播放不被中断
        /// </summary>
        private void SetHighPriority()
        {
            try
            {
                // 设置当前进程优先级为高优先级
                using (var currentProcess = Process.GetCurrentProcess())
                {
                    currentProcess.PriorityClass = ProcessPriorityClass.High;
                    System.Diagnostics.Debug.WriteLine("进程优先级已设置为: High");
                }
                
                // 设置当前线程优先级为最高
                Thread.CurrentThread.Priority = ThreadPriority.Highest;
                System.Diagnostics.Debug.WriteLine("线程优先级已设置为: Highest");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"设置高优先级失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从嵌入资源中提取音频文件到临时文件
        /// </summary>
        /// <param name="resourceName">资源名称 (如 "11.mp3")</param>
        /// <returns>临时文件路径</returns>
        private string? ExtractEmbeddedAudio(string resourceName)
        {
            try
            {
                var assembly = Assembly.GetExecutingAssembly();
                var fullResourceName = $"GameOverlayWPF.{resourceName}";
                
                System.Diagnostics.Debug.WriteLine($"尝试提取嵌入资源: {fullResourceName}");
                
                // 列出所有可用的资源名称进行调试
                var resourceNames = assembly.GetManifestResourceNames();
                System.Diagnostics.Debug.WriteLine("可用的嵌入资源:");
                foreach (var name in resourceNames)
                {
                    System.Diagnostics.Debug.WriteLine($"  - {name}");
                }
                
                using (var stream = assembly.GetManifestResourceStream(fullResourceName))
                {
                    if (stream == null)
                    {
                        System.Diagnostics.Debug.WriteLine($"未找到嵌入资源: {fullResourceName}");
                        return null;
                    }
                    
                    // 创建临时文件
                    var tempPath = Path.GetTempFileName();
                    var tempAudioPath = Path.ChangeExtension(tempPath, Path.GetExtension(resourceName));
                    File.Delete(tempPath); // 删除临时文件，使用新扩展名
                    
                    // 提取资源到临时文件
                    using (var fileStream = File.Create(tempAudioPath))
                    {
                        stream.CopyTo(fileStream);
                    }
                    
                    System.Diagnostics.Debug.WriteLine($"嵌入资源已提取到: {tempAudioPath}");
                    return tempAudioPath;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"提取嵌入资源失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 播放音频文件
        /// </summary>
        /// <param name="filePath">音频文件路径</param>
        public async Task PlayAudioAsync(string filePath)
        {
            try
            {
                // 如果启用了增强模式，使用EnhancedAudioService播放（支持麦克风输出）
                if (_useEnhancedMode)
                {
                    try
                    {
                        await EnhancedAudioService.Instance.PlayAudioAsync(filePath);
                        return;
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"增强模式播放失败，降级到基础模式: {ex.Message}");
                        // 继续使用基础模式
                    }
                }
                
                // 基础模式播放
                string actualFilePath = filePath;
                
                if (!File.Exists(filePath))
                {
                    System.Diagnostics.Debug.WriteLine($"音频文件不存在: {filePath}");
                    
                    // 尝试从嵌入资源中提取
                    var fileName = Path.GetFileName(filePath);
                    System.Diagnostics.Debug.WriteLine($"尝试从嵌入资源提取: {fileName}");
                    
                    var extractedPath = ExtractEmbeddedAudio(fileName);
                    if (extractedPath != null)
                    {
                        actualFilePath = extractedPath;
                        System.Diagnostics.Debug.WriteLine($"成功从嵌入资源提取音频文件到: {actualFilePath}");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("无法从嵌入资源提取音频文件");
                        return;
                    }
                }

                System.Diagnostics.Debug.WriteLine($"尝试播放音频文件(基础模式): {actualFilePath}");

                // 先尝试使用MediaPlayer
                bool mediaPlayerSuccess = false;
                
                // 设置当前线程为最高优先级
                Thread.CurrentThread.Priority = ThreadPriority.Highest;
                
                await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        if (_mediaPlayer != null)
                        {
                            _mediaPlayer.Stop();
                            _mediaPlayer.Close();
                            
                            var uri = new Uri(actualFilePath, UriKind.Absolute);
                            System.Diagnostics.Debug.WriteLine($"MediaPlayer URI: {uri}");
                            
                            // 清除之前的事件处理器
                            _mediaPlayer.MediaOpened -= OnMediaOpened;
                            _mediaPlayer.MediaFailed -= OnMediaFailed;
                            _mediaPlayer.MediaEnded -= OnMediaEnded;
                            
                            // 添加事件处理器
                            _mediaPlayer.MediaOpened += OnMediaOpened;
                            _mediaPlayer.MediaFailed += OnMediaFailed;
                            _mediaPlayer.MediaEnded += OnMediaEnded;
                            
                            _mediaPlayer.Open(uri);
                            
                            // 使用高优先级立即播放
                            Task.Delay(50).ContinueWith(_ =>
                            {
                                System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
                                {
                                    try
                                    {
                                        _mediaPlayer.Play();
                                        System.Diagnostics.Debug.WriteLine("MediaPlayer 高优先级播放命令已发送");
                                    }
                                    catch (Exception ex)
                                    {
                                        System.Diagnostics.Debug.WriteLine($"MediaPlayer 播放失败: {ex.Message}");
                                    }
                                }, DispatcherPriority.Send); // 使用最高优先级
                            }, TaskScheduler.Default);
                            
                            mediaPlayerSuccess = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"MediaPlayer 失败: {ex.Message}");
                        mediaPlayerSuccess = false;
                    }
                }, DispatcherPriority.Send); // 使用最高优先级
                
                // 如果MediaPlayer失败，尝试使用SoundPlayer作为备用
                if (!mediaPlayerSuccess || Path.GetExtension(actualFilePath).ToLower() == ".wav")
                {
                    await Task.Run(() =>
                    {
                        try
                        {
                            // 设置线程优先级为最高
                            Thread.CurrentThread.Priority = ThreadPriority.Highest;
                            
                            System.Diagnostics.Debug.WriteLine("尝试使用SoundPlayer高优先级播放音频");
                            using (var soundPlayer = new SoundPlayer(actualFilePath))
                            {
                                soundPlayer.Play();
                                System.Diagnostics.Debug.WriteLine("SoundPlayer 高优先级播放成功");
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"SoundPlayer 播放失败: {ex.Message}");
                        }
                    });
                }
                
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"音频播放异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常详情: {ex}");
            }
        }

        private void OnMediaOpened(object? sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("MediaPlayer: 媒体已打开");
        }

        private void OnMediaFailed(object? sender, ExceptionEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"MediaPlayer: 媒体播放失败 - {e.ErrorException?.Message}");
        }

        private void OnMediaEnded(object? sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("MediaPlayer: 媒体播放结束");
        }

        /// <summary>
        /// 停止播放
        /// </summary>
        public void Stop()
        {
            try
            {
                if (_mediaPlayer != null)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        _mediaPlayer?.Stop();
                        System.Diagnostics.Debug.WriteLine("音频播放已停止");
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"停止音频播放失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置音量
        /// </summary>
        /// <param name="volume">音量 (0.0 - 1.0)</param>
        public void SetVolume(double volume)
        {
            try
            {
                if (_mediaPlayer != null)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        _mediaPlayer.Volume = Math.Max(0.0, Math.Min(1.0, volume));
                        System.Diagnostics.Debug.WriteLine($"音量设置为: {_mediaPlayer.Volume}");
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"设置音量失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试播放功能
        /// </summary>
        public void TestPlay(string filePath)
        {
            System.Diagnostics.Debug.WriteLine($"高优先级测试播放: {filePath}");
            System.Diagnostics.Debug.WriteLine($"文件是否存在: {File.Exists(filePath)}");
            if (File.Exists(filePath))
            {
                var fileInfo = new FileInfo(filePath);
                System.Diagnostics.Debug.WriteLine($"文件大小: {fileInfo.Length} bytes");
                System.Diagnostics.Debug.WriteLine($"文件扩展名: {fileInfo.Extension}");
            }
            
            // 设置当前线程优先级为最高
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            _ = PlayAudioAsync(filePath);
        }

        /// <summary>
        /// 游戏模式下播放音频（设置为最高优先级，确保在游戏中也能播放）
        /// </summary>
        /// <param name="filePath">音频文件路径</param>
        public async Task PlayAudioInGameModeAsync(string filePath)
        {
            try
            {
                // 再次确保进程和线程优先级为最高
                SetHighPriority();
                
                System.Diagnostics.Debug.WriteLine("=== 游戏模式高优先级音频播放 ===");
                
                // 提升当前线程优先级到实时级别
                Thread.CurrentThread.Priority = ThreadPriority.Highest;
                
                // 优先使用增强模式（支持麦克风输出）
                if (_useEnhancedMode)
                {
                    try
                    {
                        await EnhancedAudioService.Instance.PlayAudioInGameModeAsync(filePath);
                        System.Diagnostics.Debug.WriteLine("=== 游戏模式音频播放完成（增强模式） ===");
                        return;
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"增强模式播放失败，降级到基础模式: {ex.Message}");
                    }
                }
                
                // 使用基础模式播放音频
                await PlayAudioAsync(filePath);
                
                System.Diagnostics.Debug.WriteLine("=== 游戏模式音频播放完成 ===");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"游戏模式音频播放失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            try
            {
                if (_mediaPlayer != null && System.Windows.Application.Current != null)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        _mediaPlayer?.Stop();
                        _mediaPlayer?.Close();
                        _mediaPlayer = null;
                        System.Diagnostics.Debug.WriteLine("音频资源已释放");
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"释放音频资源失败: {ex.Message}");
            }
        }
    }
}
